package repository

import (
	"blog_go/internal/model"
	"errors"
	"time"
)

type ArticleCategoryRepository interface {
	QueryArticleCategory() ([]*model.ArticleCategory, error)
	AddArticleCategory(categoryName string) error
	UpdateArticleCategory(articleCategory model.ArticleCategory) error
	DelArticleCategory(categoryId int) error
}

type articleCategoryRepository struct {
	*BaseRepository
}

func NewArticleCategoryRepository(repository *BaseRepository) ArticleCategoryRepository {
	return &articleCategoryRepository{
		BaseRepository: repository,
	}
}

// 查询分类
func (r *articleCategoryRepository) QueryArticleCategory() ([]*model.ArticleCategory, error) {
	categories := make([]*model.ArticleCategory, 0)

	rows, err := r.db.Query(`
		SELECT 
			category_id, 
			category_name, 
			update_time 
		FROM 
			article_category
	`)
	if err != nil {
		return nil, err
	}

	defer rows.Close()

	for rows.Next() {
		var category model.ArticleCategory

		err := rows.Scan(&category.CategoryId, &category.CategoryName, &category.UpdateTime)
		if err != nil {
			return nil, err
		}

		categories = append(categories, &category)
	}

	return categories, nil
}

// 添加分类
func (r *articleCategoryRepository) AddArticleCategory(categoryName string) error {
	//分类名不能重复
	var count int

	err := r.db.QueryRow(`
		SELECT 
			count(*) 
		FROM 
			article_category 
		WHERE 
			category_name = ?`, categoryName).Scan(&count)
	if err != nil {
		return err
	}

	if count > 0 {
		return errors.New("分类名重复")
	}

	createTime := time.Now().Format("2006-01-02 15:04:05")
	_, err = r.db.Exec(`
		INSERT INTO article_category
		(
			category_name, 
			update_time
		) 
		VALUES (?, ?)`, categoryName, createTime)
	if err != nil {
		return err
	}

	return nil
}

// 更新分类
func (r *articleCategoryRepository) UpdateArticleCategory(articleCategory model.ArticleCategory) error {
	//分类名不能重复
	var count int

	err := r.db.QueryRow(`
		SELECT 
			count(*) 
		FROM 
			article_category 
		WHERE 
			category_name = ?`, articleCategory.CategoryName).Scan(&count)
	if err != nil {
		return err
	}

	if count > 0 {
		return errors.New("分类名重复")
	}

	createTime := time.Now().Format("2006-01-02 15:04:05")
	_, err = r.db.Exec(`
		UPDATE 
			article_category 
		SET 
			category_name = ?, 
			update_time = ? 
		WHERE 
			category_id = ?`, articleCategory.CategoryName, createTime, articleCategory.CategoryId)
	if err != nil {
		return err
	}

	return nil
}

// 删除分类
func (r *articleCategoryRepository) DelArticleCategory(categoryId int) error {
	//查询分类下是否有标签，没有即可删除
	var count int

	err := r.db.QueryRow(`
		SELECT 
			COUNT(*) 
		FROM 
			article_category_tag 
		WHERE 
			category_id = ?`, categoryId).Scan(&count)
	if err != nil {
		return err
	}

	if count > 0 {
		return errors.New("分类下还有标签,不可删除")
	}

	_, err = r.db.Exec(`
		DELETE FROM article_category 
		WHERE 
			category_id = ?`, categoryId)
	if err != nil {
		return err
	}

	return nil
}
